<script lang="tsx">
import useRender from "@/utils/hooks/render";
import { computed, inject, ref } from "vue";
import FieldItem from "../field-item.vue";
import type { Column, FormListItem } from "../index.vue";
import { objByPath, useCurrPathRef } from "../utils";

// const FieldItem = Object.create(FieldItem2);

export default {
  props: {
    item: {
      type: Object as () => FormListItem,
      required: true,
    },
    parentPath: {
      type: String,
    },
  },
  setup(props, ctx) {
    const rootModal = inject<Record<string, any>>("rootModal")!;
    const changeValue =
      inject<(path: string, value: any) => void>("changeValue");
    const currPath = useCurrPathRef(props.item, props.parentPath);

    const listValue = computed<Record<string, any>[]>(() => {
      return objByPath(rootModal, currPath.value).get() || [];
    });

    const listItemTemp = computed(() => {
      const obj = {};
      const cols = [...props.item.columns] as Column[];

      while (cols.length) {
        const item = cols.shift();
        if (!item) break;

        if (item.valueType === "group") {
          cols.push(...item.columns);
          continue;
        }
        if (item.valueType === "formList") {
        }

        objByPath(obj, item.dataIndex).set(item.initValue);
      }
      return obj;
    });

    const onDel = (idx: number) => {
      console.log("del");

      listValue.value.splice(idx, 1);
      changeValue?.(currPath.value, listValue.value);
    };

    const onAdd = () => {
      console.log("add");
      listValue.value.push(JSON.parse(JSON.stringify(listItemTemp.value)));
      changeValue?.(currPath.value, listValue.value);
    };

    useRender(() => (
      <div class="formList">
        <div class="">{props.item.title}</div>
        {listValue.value.map((listitem, index) => {
          return (
            <div class="formList-item" key={listitem.dataIndex}>
              <i class="uno-ml-5" onClick={() => onDel(index)}>
                x
              </i>
              {props.item.columns.map((el) => {
                return (
                  <FieldItem
                    item={el}
                    parentPath={`${currPath.value}.${index}`}
                  ></FieldItem>
                );
              })}
            </div>
          );
        })}

        <nut-button plain type="primary" shape="square" onClick={() => onAdd()}>
          +
        </nut-button>
      </div>
    ));

    return { currPath, listValue, listItemTemp };
  },
};
</script>

<style lang="scss"></style>
